
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ListView,
    TouchableOpacity,
    Dimensions,
    ScrollView,
    RefreshControl,
    InteractionManager
} from 'react-native';
import ViewPager from "react-native-viewpager";
import ImageViewer from "./ImageViewer";
import Global from "../Commom/GlobalConst";
import SelectAddress from './SelectAddress';
import TownPage from './TownPage';
import Picker from "react-native-picker";
import URuralSearchPage from './URuralSearchPage';
import ListStrategyPage from './ListStrategyPage';
import ListActivityPage from './ListActivityPage';
import ListWithTogetherPage from './ListWithTogetherPage';
import ListQuestionAnswerPage from './ListQuestionAnswerPage';
let {width,height} = Global.Const.size;
import RCTDeviceEventEmitter from 'RCTDeviceEventEmitter'
import RuralAPIService from "../Commom/RuralAPIService";
import EventDetailsPage from './EventDetailsPage';
import WithTogetherDetails from './WithTogetherDetails';
import QuestionDetailsPage from './QuestionDetailsPage';
import StrategyDetailPage from '../Components/StrategyDetailPage';
import DateUtil from "../Commom/DateUtil";
import CarouselCard from 'react-native-card-carousel'
import Toast from '../Utils/toast';
import CountryHomePage from "./CountryHomePage";
export default class URural extends Component {
    constructor(props) {
        super(props);
        var dataSourceAllListData = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            address:'珠海市',
            banner_list:[],
            banner:[],
            about_with:{},
            activity:{},
            question_answer:{},
            strategy:{},
            dataSourceAllList: dataSourceAllListData,
            cityId:0,
            AreaList:[],
            area:'斗门区',
            areaId:'',
            TownList:[],
            ruralData:[
                {name:'斗门镇',image:require('../../Image/new/bg_01.png')},
                {name:'金台寺',image:require('../../Image/new/bg_02.png')},
                {name:'莲花村',image:require('../../Image/new/bg_03.png')},
                {name:'会同村',image:require('../../Image/new/bg_04.png')}],
            aboutWithImage:[{image:require('../../Image/new/image_01.png')},
                            {image:require('../../Image/new/image_02.png')},
                            {image:require('../../Image/new/image_03.png')}],
            ruraLibraryImages: [{image_url:"http://xc.xiarikui.cn/Public/upload/ad/2017/01-17/587ddae52620c.jpg"},{image_url:"http://xc.xiarikui.cn/Public/upload/ad/2017/01-17/587ddaf7085f3.jpg"},{image_url:"http://xc.xiarikui.cn/Public/upload/ad/2017/03-02/58b7803488aeb.png"}],
        }
    }
    componentDidMount() {
            RuralAPIService.HomeIndex().then((ret)=> {
                var banner=[];
                for(var i=0;i<ret.banner_list.length;i++){
                    banner.push(ret.banner_list[i].image);
                }
                this.setState({
                    banner_list:banner,
                    banner:ret.banner_list,
                    about_with:ret.about_with,
                    activity:ret.activity,
                    question_answer:ret.question_answer,
                    strategy:ret.strategy
                })
            }).catch((err)=> {
            });
        this.getAreaList(this.state.cityId);

    }
    onRefreshData(){
        RuralAPIService.HomeIndex().then((ret)=> {
            var banner=[];
            for(var i=0;i<ret.banner_list.length;i++){
                banner.push(ret.banner_list[i].image);
            }
            this.setState({
                banner_list:banner,
                banner:ret.banner_list,
                about_with:ret.about_with,
                activity:ret.activity,
                question_answer:ret.question_answer,
                strategy:ret.strategy
            });
            Toast.show('刷新成功');
        }).catch((err)=> {
        });
    }
    getAreaList(cityId){
        RuralAPIService.AreaList(cityId).then((ret)=> {
            this.setState({
                AreaList:ret,
                area:ret[0].name,
                areaId:ret[0].id
            });
            this.getTownList(ret[0].id);
        }).catch((err)=> {
            this.setState({
                TownList:[],
            });
        });
    }
    getTownList(areaId){
        RuralAPIService.RecommendedTown(areaId).then((ret)=> {
            this.setState({
                TownList:ret,
            })
        }).catch((err)=> {

        });
    }
    viewPagerItemClick() {
        this.props.navigator.push({
            name: 'ImageViewer',
            component: ImageViewer,
            passProps: {
                source: this.state.about_with.images,
            }
        })
    }
    ItemClick(page) {
        var type=0;
        var id=0;
        for(var i=0;i<this.state.banner.length;i++){
            if(page==this.state.banner[i].image){
                type=this.state.banner[i].type;
                id=this.state.banner[i].id;
            }
        }
        if(type==1){
            this.props.navigator.push({
                id: 'CountryHomePage',
                component: CountryHomePage,
                passProps: {
                    ID: id
                },
            });
        }else if(type==2){
            this.props.navigator.push({
                id: 'EventDetailsPage',
                component: EventDetailsPage,
                passProps: {
                    ID: id
                },
            });
        }
    }
    _renderPage(page) {
        return (
            <TouchableOpacity onPress={() => this.ItemClick(page)}>
                <View style={{ height: 200,
                    width,alignItems:'center'}}>
                    <Image source={{uri:page}} style={{
                        height: 200,
                        width:width,
                    }}/>
                </View>
            </TouchableOpacity>
        )
    }
    clonePageData() {
        let dataSource = new ViewPager.DataSource({
            pageHasChanged: (p1, p2) => p1 !== p2
        });
        return dataSource.cloneWithPages(this.state.banner_list);
    }
    selectAddress(){
        this.props.navigator.push({
            id: 'SelectAddress',
            component: SelectAddress,
            passProps: {
                address: (city,cityId) => {
                    this.getAreaList(cityId);
                    this.setState({
                        address: city,
                        cityId:cityId
                    })
                }
            }
        });
    }
    goTown(id){
        this.props.navigator.push({
            id: 'TownPage',
            component: TownPage,
            passProps: {
                ID:id
            }
        });
    }
    goURuralSearchPage(){
        this.props.navigator.push({
            id: 'URuralSearchPage',
            component: URuralSearchPage,
        });
    }

    goListActivityPage(){
        this.props.navigator.push({
            id: 'ListActivityPage',
            component: ListActivityPage,
        });
    }
    goListWithTogetherPage(){
        this.props.navigator.push({
            id: 'ListWithTogetherPage',
            component: ListWithTogetherPage,
        });
    }
    goListQuestionAnswerPage(){
        this.props.navigator.push({
            id: 'ListQuestionAnswerPage',
            component: ListQuestionAnswerPage,
        });
    }
    goListStrategyPage(){
        this.props.navigator.push({
            id: 'ListStrategyPage',
            component: ListStrategyPage,
        });
    }
    goActivityDetails(id){
        this.props.navigator.push({
            id: 'EventDetailsPage',
            component: EventDetailsPage,
            passProps: {
                ID:id
            }
        });
    }
    goAboutWith(id){
        this.props.navigator.push({
            id: 'WithTogetherDetails',
            component: WithTogetherDetails,
            passProps: {
                ID:id
            }
        });
    }
    goQA(id){
        this.props.navigator.push({
            id: 'QuestionDetailsPage',
            component: QuestionDetailsPage,
            passProps: {
                ID:id
            }
        });
    }
    goStrategyPage(id){
        this.props.navigator.push({
            id: 'StrategyDetailPage',
            component: StrategyDetailPage,
            passProps: {
                ID:id
            }
        });
    }
    selectTown(){
        var totalData=[];
        for(var i=0;i<this.state.AreaList.length;i++){
            totalData.push(this.state.AreaList[i].name);
        }
        var pickerData = totalData;
        var titleText = '';
        Picker.init({
            pickerData: pickerData,
            selectedValue: [this.state.AreaList[0].name],
            pickerTitleText: titleText,
            pickerBg: [255, 255, 255, 1],
            pickerToolBarFontSize: 14,
            pickerFontSize: 14,
            pickerToolBarBg: [245, 245, 245, 1],
            pickerTitleColor: [41, 41, 67, 1],
            pickerConfirmBtnText: '确定   ',
            pickerCancelBtnText: '   取消',
            pickerConfirmBtnColor: [41, 41, 67, 1],
            pickerCancelBtnColor: [41, 41, 67, 1],
            onPickerConfirm: pickedValue => {
                var content = pickedValue[0] ;
                for(var i=0;i<this.state.AreaList.length;i++){
                    if(content==this.state.AreaList[i].name){
                        this.getTownList(this.state.AreaList[i].id)
                    }
                }
                this.setState({
                    area:content
                })
            },
        });
        Picker.show();
    }
    GoToMap(){
        RCTDeviceEventEmitter.emit('GoToMap','1');
    }
    render() {
        var about_with_images = [];
        if(this.state.about_with!=null&&this.state.about_with!=''){
            about_with_images =this.state.about_with.images;
        }
        return (
            <View style={styles.container}>
                {/*导航栏*/}
                <View style={{width,height:64,backgroundColor:'#24CD78',flexDirection:'row',justifyContent:'space-between',paddingTop:20,alignItems:'center'}}>
                    <TouchableOpacity activeOpacity={0.5}
                                      onPress={()=>this.selectAddress()}>
                        <View style={{flexDirection:'row',width:80,height:40,marginLeft:10,alignItems:'center',}}>
                            <Text style={{color:'white'}}>{this.state.address}</Text>
                            <Image style={{width:7,height:7,resizeMode:'contain',marginLeft:3,marginTop:2}}
                                   source={require('../../Image/new/icon_pull_down.png')}/>
                        </View>
                    </TouchableOpacity>
                    <Text style={{color:'white',fontSize:19}}>U乡村</Text>
                    <TouchableOpacity activeOpacity={0.5}
                                      onPress={()=>this.goURuralSearchPage()}>
                    <View style={{flexDirection:'row',width:80,height:40,marginRight:10,justifyContent:'flex-end',alignItems:'center'}}>
                            <Image style={{width:17,height:17,resizeMode:'contain',marginLeft:8}}
                                   source={require('../../Image/new/icon_search.png')}/>
                        </View>
                    </TouchableOpacity>
                </View>
               <ScrollView  refreshControl={
                   <RefreshControl
                       refreshing={false}
                       onRefresh={() => {this.onRefreshData()}}
                       colors={['#4CAF50', '#4CAF50', '#4CAF50', '#4CAF50']}
                       progressBackgroundColor="white"
                   /> }>
                {/*广告viewpage*/}
                <View style={{width,height:200}}>
                    <ViewPager
                        isLoop={true}
                        dataSource={this.clonePageData()}
                        renderPage={(page) => this._renderPage(page)}
                        autoPlay= {true}
                    />
                </View>
                {/*推荐小镇*/}
                   {this.state.TownList&&this.state.TownList.length>0?
                       <TouchableOpacity activeOpacity={0.5}
                                         onPress={()=>this.selectTown()}>
                           <View style={{flexDirection:'row',height:40,width,justifyContent:'space-between',alignItems:'center',backgroundColor:'white',marginTop:8}}>
                               <View style={{flexDirection:'row',alignItems:'center'}}>
                                   <Text style={{color:'black',marginLeft:10,fontSize:15,fontWeight:'bold'}}>推荐小镇</Text>
                               </View>
                               <View style={{flexDirection:'row',alignItems:'center'}}>
                                   <Text>{this.state.area}</Text>
                                   <Image style={{width:10,height:13,resizeMode:'contain',marginLeft:5,marginRight:8}}
                                          source={require('../../Image/icon_go.png')}/>
                               </View>
                           </View>
                       </TouchableOpacity>:null}
                   {this.state.TownList && this.state.TownList.length>0?
                       <View style={{width,height:150,marginTop:10}}>
                           <CarouselCard
                               height={150}
                               width={width-110}
                               data={this.state.TownList}
                               one={0.708}
                               two={0.733}
                               onPress={item => {this.goTown(item.id)}}
                               contentRender={item => <View style={{width:width-115,height:150,justifyContent:'center',alignItems:'center',backgroundColor:'white'}}>
                                   <Image style={{width:width-115,height:150,resizeMode:'cover',position: 'absolute',left:0,top:0,borderRadius:5}} source={{uri:item.image}}/>
                                   <Text style={{color:'white',backgroundColor:'rgba(0,0,0,0)',fontSize:16}}>{item.name}</Text>
                               </View>}
                           />
                   </View>:null}
                {/*地图*/}
                <View style={{height:50,width,justifyContent:'center',backgroundColor:'white'}}>
                      <Text style={{color:'black',marginLeft:10,fontSize:15,fontWeight:'bold'}}>地图</Text>
                   </View>
                <View style={{width,height:170,justifyContent:'center',alignItems:'center',backgroundColor:'white'}}>
                    <TouchableOpacity activeOpacity={0.5}
                                      onPress={()=>this.GoToMap()}>
                        <Image style={{width:width-20,height:170,resizeMode:'cover',borderRadius:5}}
                               source={require('../../Image/new/map_bg.png')}/>
                    </TouchableOpacity>
                </View>
                {/*乡村活动*/}
                   {this.state.activity!=null&&this.state.activity!=''?
                       <View>
                       <View style={{flexDirection:'row',height:50,width,justifyContent:'space-between',alignItems:'center',backgroundColor:'white'}}>
                           <View style={{flexDirection:'row',alignItems:'center'}}>
                               <Text style={{color:'black',marginLeft:10,fontSize:15,fontWeight:'bold'}}>乡村活动</Text>
                           </View>
                           <TouchableOpacity activeOpacity={0.5}
                                             onPress={()=>this.goListActivityPage()}>
                               <View style={{flexDirection:'row',alignItems:'center'}}>
                                   <Text style={{marginBottom:1}}>更多</Text>
                                   <Image style={{width:10,height:13,resizeMode:'contain',marginLeft:5,marginRight:8}}
                                          source={require('../../Image/icon_go.png')}/>
                               </View>
                           </TouchableOpacity>
                       </View>
                       <View style={{width,height:170,justifyContent:'center',alignItems:'center',backgroundColor:'white'}}>
                           <Image style={{width:width-20,height:170,resizeMode:'cover',borderRadius:5}}
                                  source={{uri:this.state.activity.image}}
                           />
                       </View>
                       <View style={{flexDirection:'row',height:55,width,justifyContent:'space-between',alignItems:'center',backgroundColor:'white'}}>
                           <View style={{marginLeft:10,width:width-90,height:55}}>
                               <Text numberOfLines={1} style={{color:'black',fontSize:15,fontWeight:'bold'}}>{this.state.activity.title}</Text>
                               <Text numberOfLines={2} style={{marginTop:3,fontSize:12,lineHeight:18,color:Global.FontColor.DarkGray}}>{this.state.activity.content}</Text>
                           </View>
                           <TouchableOpacity activeOpacity={0.5}
                                             onPress={()=>  this.goActivityDetails(this.state.activity.id)}
                           >
                               <View style={{width:60,height:24,justifyContent:'center',alignItems:'center',marginRight:10,borderRadius:3,backgroundColor:'#24CD78'}}>
                                   <Text style={{color:'white',fontSize:11}}>查看详情</Text>
                               </View>
                           </TouchableOpacity>
                       </View>
                   </View>:null}

                {/*热门约伴*/}
                   {this.state.about_with!=null&&this.state.about_with!=''?
                       <View>
                       <View style={{flexDirection:'row',height:55,width,justifyContent:'space-between',alignItems:'center',backgroundColor:'white',marginTop:8,borderBottomWidth:1,borderTopWidth:8,borderColor:'#F5F5F5'}}>
                           <View style={{flexDirection:'row',alignItems:'center'}}>
                               <View style={{width:6,height:6,backgroundColor:'red',borderRadius:3,marginLeft:10,marginRight:5}}/>
                               <Text >热门约伴</Text>
                           </View>
                           <TouchableOpacity activeOpacity={0.5}
                                             onPress={()=>this.goListWithTogetherPage()}>
                               <View style={{flexDirection:'row',alignItems:'center'}}>
                                   <Text style={{marginBottom:1}}>更多</Text>
                                   <Image style={{width:10,height:13,resizeMode:'contain',marginLeft:5,marginRight:8}}
                                          source={require('../../Image/icon_go.png')}/>
                               </View>
                           </TouchableOpacity>
                       </View>
                       <View style={{flexDirection:'row',height:55,width,justifyContent:'space-between',alignItems:'center',backgroundColor:'white',marginTop:8}}>
                           <View style={{flexDirection:'row',alignItems:'center'}}>
                               <Image style={{width:30,height:30,borderRadius:15,marginLeft:10,marginRight:5}}
                                      source={{uri:this.state.about_with.author_image}}
                               />
                               <Text >{this.state.about_with.author}</Text>
                           </View>
                           <Text style={{marginRight:10}}>{DateUtil.dateStr(this.state.about_with.time)}</Text>
                       </View>
                       <Text numberOfLines={3} style={{marginLeft:10,width:width-20,lineHeight:24,color:'black'}}>{this.state.about_with.title}</Text>
                       {about_with_images&&about_with_images.length>0?
                           <View style={{width:width,marginLeft:5,flexDirection:'row',flexWrap: 'wrap',marginTop:10}}>
                               {about_with_images.map((item, index) => {
                                   return(
                                       <TouchableOpacity  style={{width:(width-30)/3,height:120,marginBottom:5,marginLeft:5}}  key={'row' + index} onPress={() => this.viewPagerItemClick()}>
                                           <Image
                                               key={'row' + index}
                                               style={{width:(width-30)/3,height:120,resizeMode:'cover'}}  source={{uri:item}}/>
                                       </TouchableOpacity>
                                   )
                               })}
                           </View>:null}
                       <View style={{flexDirection:'row',height:55,width,justifyContent:'space-between',alignItems:'center',backgroundColor:'white',marginTop:8}}>
                           <View style={{flexDirection:'row',alignItems:'center'}}>
                               <Image style={{width:18,height:18,marginLeft:10,marginRight:8,resizeMode:'contain'}}
                                      source={require('../../Image/new/image_car.png')}
                               />
                               <Text >自驾约伴</Text>
                           </View>
                           <TouchableOpacity activeOpacity={0.5}
                                             onPress={() => this.goAboutWith(this.state.about_with.id)}
                           >
                               <View style={{width:60,height:24,justifyContent:'center',alignItems:'center',marginRight:10,borderRadius:3,backgroundColor:'#24CD78'}}>
                                   <Text style={{color:'white',fontSize:12}}>参加</Text>
                               </View>
                           </TouchableOpacity>
                       </View>
                   </View>:null}

                {/*热门问答*/}
                   {this.state.question_answer!=null&&this.state.question_answer!=''?
                       <View>
                       <View style={{flexDirection:'row',height:55,width,justifyContent:'space-between',alignItems:'center',backgroundColor:'white',marginTop:8,borderBottomWidth:1,borderTopWidth:8,borderColor:'#F5F5F5'}}>
                           <View style={{flexDirection:'row',alignItems:'center'}}>
                               <View style={{width:6,height:6,backgroundColor:'#F2B94C',borderRadius:3,marginLeft:10,marginRight:5}}/>
                               <Text >热门问答</Text>
                           </View>
                           <TouchableOpacity activeOpacity={0.5}
                                             onPress={()=>this.goListQuestionAnswerPage()}>
                               <View style={{flexDirection:'row',alignItems:'center'}}>
                                   <Text style={{marginBottom:1}}>更多</Text>
                                   <Image style={{width:10,height:13,resizeMode:'contain',marginLeft:5,marginRight:8}}
                                          source={require('../../Image/icon_go.png')}/>
                               </View>
                           </TouchableOpacity>
                       </View>
                       <View style={{flexDirection:'row',height:55,width,justifyContent:'space-between',alignItems:'center',backgroundColor:'white',marginTop:8}}>
                           <View style={{flexDirection:'row',alignItems:'center'}}>
                               <Image style={{width:30,height:30,borderRadius:15,marginLeft:10,marginRight:5}}
                                      source={{uri:this.state.question_answer.author_image}}
                               />
                               <Text >{this.state.question_answer.author}</Text>
                           </View>
                           <Text style={{marginRight:10}}>{DateUtil.dateStr(this.state.question_answer.time)}</Text>
                       </View>
                       <Text numberOfLines={3} style={{marginLeft:10,width:width-20,lineHeight:24,color:'black'}}>{this.state.question_answer.title}
                       </Text>
                       <View style={{flexDirection:'row',height:55,width,justifyContent:'space-between',alignItems:'center',backgroundColor:'white',marginTop:8}}>
                           <View style={{flexDirection:'row',alignItems:'center'}}>
                               <Image style={{width:18,height:18,marginLeft:10,marginRight:8,resizeMode:'contain'}}
                                      source={require('../../Image/new/icon_ask.png')}
                               />
                               <Text >有问必答</Text>
                           </View>
                           <TouchableOpacity activeOpacity={0.5}
                                             onPress={()=>this.goQA(this.state.question_answer.id)}>
                               <View style={{width:60,height:24,justifyContent:'center',alignItems:'center',marginRight:10,borderRadius:3,backgroundColor:'#F2B94C'}}>
                                   <Text style={{color:'white',fontSize:12}}>有赏问答</Text>
                               </View>
                           </TouchableOpacity>
                       </View>
                   </View>:null}

                {/*推荐攻略*/}
                   {this.state.strategy!=null&&this.state.strategy!=''?
                       <View>
                       <View style={{flexDirection:'row',height:55,width,justifyContent:'space-between',alignItems:'center',backgroundColor:'white',marginTop:8,borderTopWidth:8,borderColor:'#F5F5F5'}}>
                           <View style={{flexDirection:'row',alignItems:'center'}}>
                               <View style={{width:6,height:6,backgroundColor:'#24CD78',borderRadius:3,marginLeft:10,marginRight:5}}/>
                               <Text >推荐攻略</Text>
                           </View>
                           <TouchableOpacity activeOpacity={0.5}
                                             onPress={()=>this.goListStrategyPage()}>
                               <View style={{flexDirection:'row',alignItems:'center'}}>
                                   <Text style={{marginBottom:1}}>更多</Text>
                                   <Image style={{width:10,height:13,resizeMode:'contain',marginLeft:5,marginRight:8}}
                                          source={require('../../Image/icon_go.png')}/>
                               </View>
                           </TouchableOpacity>
                       </View>
                       <TouchableOpacity activeOpacity={0.5}
                                         onPress={()=>this.goStrategyPage(this.state.strategy.id)} >
                           <View style={{width:width-20,height:180,marginLeft:10,borderRadius:5}}>
                               <Image style={{width:width-20,height:180,resizeMode:'cover',borderRadius:5}}
                                      source={{uri:this.state.strategy.image}}/>
                               <View style={{position: 'absolute',left:0,bottom:0,backgroundColor:'rgba(0,0,0,0.5)',width:width-20,height:30,justifyContent:'center',borderBottomLeftRadius:5,borderBottomRightRadius:5}}>
                                   <Text style={{color:'white',marginLeft:8}}>{this.state.strategy.title}</Text>
                               </View>
                           </View>
                       </TouchableOpacity>
                   </View>:null}
                   <View style={{width,height:15}}/>
              </ScrollView>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white',
    },
});